<script>
// 获取文件列表

import {qaRequest} from "@/utils";
import {Refresh, Delete } from '@element-plus/icons-vue';
import { ElMessage } from "element-plus";
const delay = 5000
export default {
    data() {
        return {
            tableData: [],
            playSearch: false,
            timer: null
        }
    },
    created() {
        this.getFileList();
    },
    beforeUnmount() {
        clearTimeout(this.timer)
        this.timer = null
    },
    methods: {
        continueSearch() {
            this.timer = setTimeout(() => {
                this.getFileList()
            }, 3000)

        },
        async getFileList(type) {
            try {
                const response = await qaRequest({
                    url: '/datasets/0fff1337-04fc-47d7-b1ba-126463d177af/documents',
                    method: 'GET'
                });

                const {data} = response.data
                if (data) {
                    this.tableData = response.data.data.reverse().map(item => ({
                        id: item.id,
                        fileName: item.data_source_detail_dict.upload_file.name,
                        status: this.getStatusText(item.indexing_status),
                        file_id:item.data_source_info.upload_file_id,
                        // rawData: item
                    }));
                    const hasPending = data.some(item => item.indexing_status == 'waiting' || item.indexing_status == 'indexing')
                    if (hasPending) {
                        this.continueSearch()
                    }
                    if (type === 'refresh') {
                        ElMessage.success('刷新成功列表')
                    }
                } else {
                    ElMessage.error('刷新失败')
                }
            } catch (error) {
                console.error('获取文件列表失败:', error);
                this.$message?.error('文件加载失败');
                this.tableData = [];
            }
        },
        getStatusText(status) {
            const statusMap = {
                completed: '已完成',
                indexing: '处理中',
                waiting: '排队中'
            };
            return statusMap[status] || '未知状态';
        },
        getStatusType(statusText) {
            const typeMap = {
                '已完成': 'success',  // 绿色
                '处理中': 'warning',  // 黄色
                '排队中': 'info',     // 蓝色
                '未知状态': ''        // 默认无特殊颜色
            };
            return typeMap[statusText] || '';
        },
        async handleDelete(row) {
            try {
                await this.$confirm('确认删除该文件吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                await qaRequest({
                    url: `datasets/0fff1337-04fc-47d7-b1ba-126463d177af/documents/${row.id}`,
                    method: 'DELETE'
                });

                this.$message.success('删除成功');
                this.getFileList(); // 刷新列表
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败:', error);
                    this.$message.error('删除失败');
                }
            }
        },
        async refreshStatus(row) {
            // try {
            //     const response = await qaRequest({
            //         url: `datasets/0fff1337-04fc-47d7-b1ba-126463d177af/documents/${row.file_id}/indexing-status`,
            //         method: 'GET'
            //     });
            //
            //     // 更新当前行的状态
            //     row.status = this.getStatusText(response.data.indexing_status);
            //
            //     this.$message.success('状态刷新成功');
            // } catch (error) {
            //     console.error('刷新状态失败:', error);
            //     this.$message.error('状态刷新失败');
            // }
            this.getFileList('refresh')
        },
        async handleUpload() {
            try {
                // 创建文件选择input元素
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = '.txt,.md,.mdx,.pdf,.html,.xlsx,.xls,.docx,.csv,.htm,text/plain,text/markdown,application/pdf,text/html,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/csv'; // 允许所有文件类型
                input.onchange = async (event) => {
                    const file = event.target.files[0];
                    if (!file) return;

                    // 创建FormData对象
                    const formData = new FormData();
                    formData.append('file', file);
                    formData.append('data', '{"indexing_technique":"high_quality","process_rule":{"rules":{"pre_processing_rules":[{"id":"remove_extra_spaces","enabled":true},{"id":"remove_urls_emails","enabled":true}],"segmentation":{"separator":"\\n\\n","max_tokens":500}},"mode":"custom"}}'); // 根据API要求添加data字段

                    try {
                        // 显示加载状态
                        this.$message.info('文件上传中...');

                        // 调用上传API
                        const response = await qaRequest({
                            url: 'datasets/0fff1337-04fc-47d7-b1ba-126463d177af/document/create-by-file',
                            method: 'POST',
                            data: formData
                        });

                        this.$message.success('文件上传成功');
                        setTimeout(()=>{this.getFileList()},500)
                         // 刷新文件列表
                    } catch (error) {
                        console.error('上传失败:', error);
                        this.$message.error('文件上传失败,请检查文件格式和大小（不超过15MB）');
                    }
                };

                // 触发文件选择对话框
                input.click();
            } catch (error) {
                console.error('上传出错:', error);
                this.$message.error('上传过程出错');
            }
        }
    }
}
</script>
<template>
    <h1 class="pageTitle">安全知识库管理</h1>
    <div class="header-section">
        <el-tooltip
        class="box-item"
        effect="dark"
        content="文件文本格式建议分段清晰，以免影响解析效果"
        placement="bottom"
      >
      <div class="upload-btn">

            <el-button
                  
            
                    style="margin-right: 5%;margin-left: 20px;"
                    type="primary"

                    @click="handleUpload"
            >
                <i class="el-icon-upload"></i> 文件上传

            </el-button>
        </div>
    </el-tooltip>

    </div>
    <div class="file-table-container">
        <el-table
                :data="tableData"
                style="width: 100%"

                stripe
        >
            <!-- 序号列 -->
            <el-table-column
                    label="序号"
                    width="80"
                    align="center"
            >
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>

            <!-- 文件名列 -->
            <el-table-column
                    prop="fileName"
                    label="安全知识文件名"
                    min-width="200"
            />

            <!-- 文件状态列 -->
            <el-table-column
                    prop="status"
                    label="文件状态"
                    width="120"
                    align="center"
            >
                <template #default="scope">
                    <el-tag size="large" :type="getStatusType(scope.row.status)">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>

            <!-- 操作列（删除按钮） -->
            <el-table-column
                    label="操作"
                    width="200"
                    align="center"
            >
                <template #default="scope">
                    <div style="display: flex; gap: 8px; justify-content: center">
                        <el-button

                            type="primary"

                            @click="refreshStatus(scope.row)"

                            style="padding: 8px 12px; line-height: 1; text-align: center;"
                        >
                        <svg style="width: 13px; margin-right: 5px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M771.776 794.88A384 384 0 0 1 128 512h64a320 320 0 0 0 555.712 216.448H654.72a32 32 0 1 1 0-64h149.056a32 32 0 0 1 32 32v148.928a32 32 0 1 1-64 0v-50.56zM276.288 295.616h92.992a32 32 0 0 1 0 64H220.16a32 32 0 0 1-32-32V178.56a32 32 0 0 1 64 0v50.56A384 384 0 0 1 896.128 512h-64a320 320 0 0 0-555.776-216.384z"></path></svg>
                        刷新状态</el-button>
                        <el-button
                            type="danger"

                            @click="handleDelete(scope.row)"
                            style="padding: 8px 12px; line-height: 1; text-align: center;"
                        >
                        <svg style="width: 13px; margin-right: 5px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M160 256H96a32 32 0 0 1 0-64h256V95.936a32 32 0 0 1 32-32h256a32 32 0 0 1 32 32V192h256a32 32 0 1 1 0 64h-64v672a32 32 0 0 1-32 32H192a32 32 0 0 1-32-32zm448-64v-64H416v64zM224 896h576V256H224zm192-128a32 32 0 0 1-32-32V416a32 32 0 0 1 64 0v320a32 32 0 0 1-32 32m192 0a32 32 0 0 1-32-32V416a32 32 0 0 1 64 0v320a32 32 0 0 1-32 32"></path></svg>
                        删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>


<style scoped>
.file-table-container {
    padding: 20px;
    background: #fff;
    width: 90%;
    border-radius: 4px;
    margin: auto;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    max-height: 75%;
}

/* 新增的标题和上传按钮样式 */
.header-section {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 40px;
}
.el-button--small {
    min-width: 80px;  /* 设置最小宽度 */
    padding: 8px 12px !important;  /* 调整内边距 */
}

.upload-btn {

    display: flex;
}
</style>
